var malfunctionTableInit=function(){
    var oTableInit = {};
    oTableInit.init=function(){

        $('#malfunctionTable').bootstrapTable({
            url: ctx +'/equipLifeCycle/malfunction/record/listRecords/get.mvc',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
//            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            paginationLoop:false,
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "pkId",                     //每一行的唯一标识，一般为主键列
            showToggle:false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            singleSelect:false,                    //禁止多选
            checkboxHeader:true,                 //列头取消多选
            columns: [
                {
                    checkbox:true,
                    align : 'center',
                    valign : 'middle'
                },
                {
                    title: '序号',
                    align : 'center',
                    valign : 'middle',
                    formatter : function (value, row, index){
                        var options = $('#malfunctionTable').bootstrapTable('getOptions');
                        return options.pageSize * (options.pageNumber - 1) + index + 1;
                    }
                }, {
                    field: 'failureStatus',
                    title: '故障状态',
                    sortable:false,
                    align : 'center',
                    valign : 'middle',
                    formatter : function (value, row, index){
                        return "待提交";
                    }
                }, {
                    field: 'happenDate',
                    title: '故障时间',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'
                }, {
                    field: 'factoryName',
                    title: '厂区',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                }, {
                    field: 'lineName',
                    title: '产线',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                },
                {
                    field: 'shopName',
                    title: '车间',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                },
                {
                    field: 'areaName',
                    title: '区域',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                },{
                    field: 'equipName',
                    title: '设备名称',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'
                }, {
                    field: 'equipCode',
                    title: '设备编号',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                },{
                    field: 'failureShortName',
                    title: '故障标题',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                },{
                    field: 'ifStop',
                    title: '是否停机',
                    sortable:false,
                    align : 'center',
                    valign : 'middle',
                    formatter : function (value, row, index){
                        if(value == '0'){
                            return "是";
                        }else{
                            return "否";
                        }
                    }

                },
                {
                    field: 'createDate',
                    title: '登记时间',
                    sortable:false,
                    align : 'center',
                    valign : 'middle'

                }, {
                    field: 'pkId',
                    title: 'pkId',
                    visible:false
                }]

        });

    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        return {   // 这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            size: params.limit,   // 页面大小
            num: (params.offset/params.limit) + 1,  // 页码
            sort: params.sort,
            order: params.order,
            failureStatus:0

        }
    };
    return oTableInit;
}



var malfunctionInfoInit = function(){
    var _initMalfunctionTypeSelect2;
    return {
        _init : function(){
            malfunctionInfoInit.getQueryEquipCode();
            malfunctionInfoInit._refresh();
            malfunctionInfoInit._register();
            malfunctionInfoInit._validatorForm();
            malfunctionInfoInit._submit_register();
            malfunctionInfoInit._submit();
            malfunctionInfoInit._process();
            malfunctionInfoInit.malfunctionDemoSelect();
            malfunctionInfoInit.getmalfunctionDemo();
            _initMalfunctionTypeSelect2 = malfunctionInfoInit._initMalfunctionTypeSelect2();
        },
        getQueryEquipCode: function () {
            //报告人搜索
            var select2 = $("#queryEquip").select2({
                ajax: {
                    url: ctx + '/equipment/register/searchEquipmentByEquipCode/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        return {
                            equipCode: params.term,
                            num: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (result) {
                        var equipModelArr = [];
                        for (var i = 0; i < result.data.length; i++) {
                            var obj = {};
                            obj.id = result.data[i].equipCode;
                            obj.text = result.data[i].equipCode;
                            equipModelArr.push(obj);
                        }
                        return {
                            results: equipModelArr,
                            pagination: {
                                more: result.result
                            }
                        };
                    },
                    cache: true
                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 0
            });
            return select2;
        },
        //故障分类
        _initMalfunctionTypeSelect2:function () {
            var select2 = $('.malfunctionType').select2({
                ajax: {
                    url: ctx +'/system/dict/getMalfunctionTypeByDictValue/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        return {
                            search: params.term,
                            page: params.page || 1,
                            size: 10,
                        };
                    },
                    processResults: function (response) {
                        var test =[];
                        if(response.result === true&&response.data) {
                            var _data = response.data;
                            for ( var int = 0; int < _data.length; int++) {
                                var obj= {};
                                obj.id=_data[int].dictKey;
                                obj.text=_data[int].dictValue;
                                test.push(obj);
                            }
                        }
                        return {
                            results: test
                        };
                    },
                    cache: true

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0
            });
            return select2;
        },
        _refresh : function(){
            $("#refresh-table").off("click").on("click",function(){
                $('#malfunctionTable').bootstrapTable('refresh');
            })
        },
        _register : function(){
            $("#register").off("click").on("click",function(){

                /*$('.happenDate').val(new Date().format('yyyy-MM-dd hh:mm:ss'));*/
                $("#status").val('待提交');
                var aidSelect =malfunctionInfoInit._reportUser();
                var option = new Option(
                    loginTrueName,
                    loginUsername,true,true);
                aidSelect.append(option);
                aidSelect.trigger("change");
                $.fn.modal.Constructor.prototype.enforceFocus = function() {
                    $("#myModal select").focus();
                };

                $("#myModal").modal();
            })
        },
        malfunctionDemoSelect:function(){
            //报告人搜索
            var malfunctionDemo =$(".malfunctionDemo").select2({
                ajax: {
                    url: ctx +'/equipLifeCycle/malfunction/demo/selectDemoByTitle/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        var query = {
                            search: params.term,
                            num: params.page || 1,
                            size:10
                        };
                        return query;
                    },
                    processResults: function (result) {

                        var equipModelArr =new Array();
                        for ( var i = 0; i < result.data.length; i++) {
                            var obj = new Object();
                            obj.id=result.data[i].pkId;
                            obj.text=result.data[i].malfunctionTitle;
                            equipModelArr.push(obj);
                        }
                        var result = {
                            results: equipModelArr,
                        };
                        return result;
                    },
                    cache: true
                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0
            });

            return malfunctionDemo;
        },
        getmalfunctionDemo:function () {
            $(".malfunctionDemo").on("change",function (e) {
                e.preventDefault();
                $.ajax({
                    url: ctx + '/equipLifeCycle/malfunction/demo/getDemoById/get.mvc',
                    type:"post",
                    dataType:'json',
                    data : {
                        pkId : $(".malfunctionDemo").val()
                    },
                    success : function(response){
                        if (response.result == true ) {
                            var _data = response.data;
                            $("#myModal select[name='failureLevel']").val(response.data.malfunctionGrade);
                            if($("#myModal .failureTitle").val()===""){
                                $("#myModal .failureTitle").val(response.data.malfunctionTitle);
                            }
                            $("#myModal .failureDesc").val(response.data.malfunctionDesc);
                            var malfunctionType = _data.malfunctionType;
                            var malfunctionTypeValue = _data.malfunctionTypeValue;
                            if(malfunctionType!==''&&malfunctionTypeValue!=='') {
                                var option = new Option(malfunctionTypeValue,malfunctionType,true,true);
                                _initMalfunctionTypeSelect2.append(option);
                                _initMalfunctionTypeSelect2.trigger("change");
                            }
                        }else {
                            DialogUtil.error(response.message);
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        DialogUtil.error(errorThrown);
                    }
                });
            })
        },
        _reportUser:function(){
            //报告人搜索
            var user =$(".reportMan").select2({
                ajax: {
                    url: ctx +'/system/user/getAllUserLists/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        var query = {
                            username: params.term,
                            num: params.page || 1,
                            size:10
                        };
                        return query;
                    },
                    processResults: function (result) {

                        var equipModelArr =new Array();
                        for ( var i = 0; i < result.data.length; i++) {
                            var obj = new Object();
                            obj.id=result.data[i].username;
                            obj.text=result.data[i].truename;
                            equipModelArr.push(obj);
                        }
                        var result = {
                            results: equipModelArr,
                            pagination :{
                                more:result.result
                            }
                        };
                        return result;
                    },
                    cache: true
                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
                minimumInputLength: 0
            });

            return user;
        },

        _submit_register : function(){
            //设备编号更改事件
            $(".queryEquipment").on("change",function(){
                var equipCode =$(".queryEquipment").val();
                $.ajax({
                    url:ctx+"/equipment/register/equipCodeChangeByeqCode/get.mvc",
                    type:"get",
                    dataType:"json",
                    data:{
                        equipCode:equipCode},
                    success : function(response){
                        if (response.result == true) {
                            //获取对应的数据
                            $("#myModal .equipName").val(response.data.equipName);
                            $("#myModal .factoryName").val(response.data.fatoryName);
                            $("#myModal .lineName").val(response.data.lineName);
                            $("#myModal .shopName").val(response.data.shopName);
                            $("#myModal .areaName").val(response.data.areaName);
                            $("#myModal .dutyUser").val(response.data.responsiblePerson);
                            $("#myModal .department").val(response.data.department);

                        }else {
                            DialogUtil.warning(response.message);
                        }

                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown){
                        DialogUtil.warning("系统错误");
                    }

                })
            })



            //故障时间
            $('.happenDate').datetimepicker({
                format : 'yyyy-mm-dd hh:ii:ss',
                language : 'zh-CN',
                autoclose:true,
                pickerPosition: "bottom-left",
                endDate : new Date(),
                forceParse : true
            });
            //文件上传
            $("#uploadfile").fileinput({

                language: 'zh', //设置语言

                uploadUrl: ctx +'/equipment/register/savePhoto/save.mvc', //上传的地址

                allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀

                //uploadExtraData:{"id": 1, "fileName":'123.mp3'},

                uploadAsync: true, //默认异步上传

                showUpload: false, //是否显示上传按钮
                showRemove :false, //显示移除按钮

                showPreview : true, //是否显示预览

                showCaption:false,//是否显示标题

                browseClass:"btn btn-primary", //按钮样式

                dropZoneEnabled: false,//是否显示拖拽区域

                maxFileSize:300,//单位为kb，如果为0表示不限制文件大小

                maxFileCount: 1, //表示允许同时上传的最大文件个数

                enctype:'multipart/form-data',

                validateInitialCount:false,

                previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>",

                msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",

            }).on("fileuploaded", function (event, data, previewId, index){//上传成功后立即执行
                console.log(data.response.path);
                $('.btn-file').hide();
                $("#uploadfilePath").val(data.response.path);
                /*$(".error-tips").css("display","none");*/
                //   $(".file-input-new").attr("disabled",true);
            }).on('filesuccessremove', function(event, id) {//点击删除后立即执行
                console.log("del");
                $('.btn-file').show();
                $("#uploadfilePath").val("");
                /*$(".error-tips").css("display","block");*/
            });
        },

        //校验表单
        _validatorForm : function(){
            $("#defaultForm").bootstrapValidator({
                message: 'This value is not valid',
                live: 'submitted',
                fields: {/*验证*/
                    equipCode: {
                        message: '设备编号无效',
                        validators: {
                            notEmpty: {
                                message: '请选择设备编号'
                            },
                        }
                    },
                    reportMan: {
                        message: '报告人无效',
                        validators: {
                            notEmpty: {
                                message: '请选择报告人'
                            },
                        }
                    },

                    happenDate: {
                        trigger:'change',
                        message: '故障时间',
                        validators: {
                            notEmpty: {
                                message: '故障时间为空'
                            },
                        }
                    },

                    failureTitle: {
                        message: '故障标题无效',
                        validators: {
                            notEmpty: {
                                message: '故障标题不能为空'
                            },
                            stringLength: {
                                max: 20,
                                message: '故障标题不能超过20个字符'
                            }
                        }
                    }/*,
	                failureDesc: {
	                    message: '故障详细描述无效',
	                    validators: {
	                        notEmpty: {
	                            message: '故障详细描述不能为空'
	                        }
	                    }
	                },
	                filePath: {
	                    message: '上传图片无效',
	                    validators: {
	                        notEmpty: {
	                            message: '请先上传图片'
	                        }
	                    }
	                },*/
                }
            });

            //模态框消失清空信息
            $("#myModal").off("hidden.bs.modal").on("hidden.bs.modal",function(e){
                $('#myModal input').each(function() {
                    if ($(this).val() != "" || $(this).prop('checked') == true) {
                        $(this).val("").prop('checked', false);
                    }
                });
                //清空图片
                $(".queryEquipment").attr("title", "");
                $(".queryEquipment").empty();//中间catId2是你select下拉框的id
                $(".queryEquipment").prepend('<option value=""> -- 请选择 -- </option>');
                $(".queryEquip").val(null).trigger("change");
                $(".malfunctionDemo").val(null).trigger("change");
                $(".malfunctionType").val(null).trigger("change");
                $('.fileinput-remove').trigger('click');
                $('.btn-file').show();
                $('#defaultForm').data('bootstrapValidator').destroy();
                malfunctionInfoInit._validatorForm();
            });

        },

        _submit : function(){
            $("#myModal .yes").off("click").on("click",function(){
                malfunctionInfoInit._validatorForm();
                $("#defaultForm").data("bootstrapValidator").validate();
                var flag = $("#defaultForm").data("bootstrapValidator").isValid();
                if(!flag){
                    //未通过验证
                    return false;
                }

                $('#defaultForm').data('bootstrapValidator').destroy();
                malfunctionInfoInit._validatorForm();

                //文件是否上传
                var filePath = $("#uploadfilePath").val();
                console.log("12--"+filePath);
                /*if(filePath == ""){
                    $(".error-tips").css("display","block");
                    return false;
                }*/


                var formData = new FormData($("#defaultForm")[0]);
                $.ajax({
                    url : ctx + '/equipLifeCycle/malfunction/record/registerRecord/add.mvc',
                    type : "post",
                    dataType : 'json',
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    data : formData,
                    success : function(response) {
                        if (response.result == true) {
                            DialogUtil.ok("保存成功");
                            //取消
                            $('#myModal').modal('hide');
                            $('#malfunctionTable').bootstrapTable('refresh');
                        }else{
                            DialogUtil.warning(response.message);
                        }
                    },
                    error : function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("系统错误");
                    }
                });


            })


        },
        _process:function(){
            $("#submit_register").on("click",function(){

                var ids = $.map($('#malfunctionTable').bootstrapTable('getSelections'), function (row) {
                    return row.pkId;
                });
                if (ids.length <= 0 ) {
                    DialogUtil.ok("请选择需要操作的记录");
                    return;
                }
                DialogUtil.ok_and_cancel("是否提交？",function(){
                    $.ajax({
                        url: ctx + '/equipLifeCycle/malfunction/record/submint/update.mvc',
                        type:"post",
                        dataType:'json',
                        data : {
                            recordIds : ids.toString()
                        },
                        success : function(response){
                            if (response.result == true) {
                                DialogUtil.warning("提交成功");
                                $('#malfunctionTable').bootstrapTable('refresh');
                            }else {
                                DialogUtil.warning(response.message);
                            }

                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown){
                            DialogUtil.warning("系统错误");
                        }
                    });
                },function(){});



            })

        }



    }
}();
jQuery(document).ready(function() {
    //初始化页面
    malfunctionInfoInit._init();
    var oTable = new malfunctionTableInit();
    oTable.init();

});
